<script>
	export default {
		onLaunch: function() {
			console.log('App Launch')
		},
		onShow: function() {
			console.log('App Show')
			this.createMQTT();
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			randomName(len) {
				var len = len || 23;
				var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
				var maxPos = chars.length;
				var str = '';
				for (let i = 0; i < len; i++) {
					str += chars.charAt(Math.floor(Math.random() * maxPos));
				}
				return new Date().getTime() + str;
			},
			createMQTT() {
				var that = this;
				this.$store.commit('modifyClientId', this.randomName(16)) //改变clientid
				var url = "www.huanchenxinnengyuan.com/mqtt";
				
				// 改变client
				// #ifdef H5
				var preStr = "wss://";
				var mqtt = require('mqtt'); //改变mqtt,h5可以直接写'mqtt'
				// #endif
				// #ifdef MP-WEIXIN||APP-PLUS
				var preStr = "wxs://";
				var mqtt = require('mqtt/dist/mqtt.js'); //小程序必须写'mqtt/dist/mqtt.js'
				// #endif
				
				var client = mqtt.connect(preStr + url, this.$store.getters.getState.MQTT_OPTIONS);
				this.$store.commit('modifyClient', client);
				this.$store.getters.getState.client.on('connect', function() {
					console.log('MQTT client is connected');
				}).on('error', (e) => {
					console.log('MQTT error:', e);
				}).on('reconnect', function() {
					console.log('MQTT client is reconnect...');
				}).on('message', function(topic, message) {
					console.log('topic:', topic);
					console.log("message: ", message.toString());
					that.$store.commit('modifyMsg', message.toString());
					console.log("双双:",that.$store.getters.getState);
				}).on('close', function() {
					console.log('MQTT connection closed, now exiting.');
				});
			}
		}
	}
</script>

<style>
	/*每个页面公共css */
</style>
